#include "../util/Singleton.h"
#include "../global/QmlNames.h"
#include "AudioPlayer.h"

X_BEGIN_NAMESPACE

/**
 * @brief 声音播放器，可播放系统声音或指定的声音文件。
 *
 * 此处有很多参数可以设置成配置，目前先使用硬编码。
 */

/**
 * @brief 构造函数。
 *
 * @param parent
 */
AudioPlayer::AudioPlayer(QObject *parent) : QObject(parent)
{
    initSystemSound();
}

AudioPlayer *AudioPlayer::createInstance()
{
    return new AudioPlayer;
}

/**
 * @brief 初始化播放器属性。
 */
void AudioPlayer::initMediaPlayer()
{
    m_player.setVolume(100);
}

const char *AudioPlayer::qmlName() { return QmlNames::Utils::AudioPlayerSingleton; }

QObject *AudioPlayer::qmlInstance(QQmlEngine *engine, QJSEngine *scriptEngine)
{
    Q_UNUSED(engine);
    Q_UNUSED(scriptEngine);

    return &instance();
}

AudioPlayer &AudioPlayer::instance()
{
    return *Singleton<AudioPlayer>::instance(AudioPlayer::createInstance);
}

void AudioPlayer::playSystemSound(AudioPlayer::SystemSoundType type)
{
    QString fileName = m_systemSounds[type];
    playAudioFile(fileName);
}

void AudioPlayer::playAudioFile(const QString &fileName)
{
    if(!fileName.startsWith("file://") && !fileName.startsWith("qrc:/")){
        m_player.setMedia(QUrl("file://" + fileName));
    } else {
        m_player.setMedia(QUrl(fileName));
    }
    m_player.play();
}

void AudioPlayer::onPause()
{
    m_player.pause();
}

void AudioPlayer::onResume()
{
    m_player.play();
}

void AudioPlayer::onStop()
{
    m_player.stop();
}

void AudioPlayer::initSystemSound()
{
    if(m_systemSounds.size() > 0) return;

    m_systemSounds[LoginOk] = "qrc:/audio/login.ok.mp3";
    m_systemSounds[LoginFailed] = "qrc:/audio/login.failed.mp3";
    m_systemSounds[Logout] = "qrc:/audio/logout.mp3";
    m_systemSounds[IncomingMessage] = "qrc:/audio/msg.wav";
    m_systemSounds[OutgoingMessage] = "qrc:/audio/msg.wav";
    m_systemSounds[SystemNotification] = "qrc:/audio/system.notification.wav";
    m_systemSounds[AudioCall] = "qrc:/audio/audio.call.wav";
    m_systemSounds[VideoCall] = "qrc:/audio/video.call.wav";
    m_systemSounds[Screenshot] = "qrc:/audio/screenshot.wav";
}

X_END_NAMESPACE
